package com.edisoncgh.controller;


import com.edisoncgh.pojo.Users;
import com.edisoncgh.service.impl.UsersServiceImpl;
import com.mysql.cj.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;

@Controller
@RequestMapping("/loginCheck")
public class LoginController {
    @Autowired
    private UsersServiceImpl usersService;


    @RequestMapping("/login")
    public String loginCheck(HttpServletRequest request, HttpServletResponse response) throws IOException {
        if(request.getParameter("userId") == null || request.getParameter("userPassword") == null) {
//            返回登录页面
            return "login";
        }else {
            String userid = request.getParameter("userId");
            String userpass = request.getParameter("userPassword");
            Users admin = usersService.getById(userid);
//            调试
            System.out.println(userid + " " + userpass);
//            判断
            if(admin != null) {
                if(admin.getPwd().equals(userpass)) {
                    request.getSession().setAttribute("msg", "登录成功");
                    request.getSession().setAttribute("userId", userid);
                    request.getSession().setAttribute("mention", null);
                    return "index";
                }else {
                    request.getSession().setAttribute("msg", "登陆失败");
                    return "login";
                }
            }else {
                request.getSession().setAttribute("msg", "用户不存在");
                return "login";
            }
        }
    }

    @RequestMapping("/loginOut")
    public String loginOut(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.getSession().setAttribute("mention", "您还未登录！");
        Object admin = request.getSession().getAttribute("userId");
        if(admin != null) {
//            登出时删除session中的该用户信息,同时刻只会存在一个用户
            request.getSession().removeAttribute("userId");
        }
        return "index";
    }
}
